package cn.donting.web.desktop.sys.controller;

import cn.donting.web.desktop.core.domain.ResponseEntity;
import cn.donting.web.desktop.core.exception.AppException;
import cn.donting.web.desktop.core.entity.User;
import cn.donting.web.desktop.sys.service.UserCenter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author donting
 * 2021-06-06 下午8:57
 */
@RestController
@RequestMapping("/sys/user")
@Slf4j
public class UserController {

    @Autowired
    UserCenter userService;

    /**
     * 创建用户
     * @param user
     * @return
     */
    @PostMapping
    public ResponseEntity creatUser(@RequestBody User user) {
        try {
            user = userService.creatUser(user.getName(), user.getPassword());
            return ResponseEntity.ok(user);
        } catch (AppException e) {
            log.error(e.getMessage(), e);
            return ResponseEntity.error(1502, e.getMessage());
        }

    }
    /**
     * 登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody User user, HttpServletResponse response) throws IOException {
        User login = userService.login(user.getName(), user.getPassword());
        if(login==null){
           return ResponseEntity.error(500,"密码错误");
        }
        return ResponseEntity.ok(login);

    }
    /**
     * 获取登录用户
     * @param
     * @return
     */
    @GetMapping("/loginUser")
    public ResponseEntity loginUser() throws IOException {
        return ResponseEntity.ok(userService.getLoginUser());
    }

    /**
     * 登出
     * @return
     * @throws IOException
     */
    @GetMapping("/logout")
    public ResponseEntity logout() throws IOException {
        return ResponseEntity.ok(userService.logout());
    }


}
